<template>
  <div id="cart">
    <el-table
        ref="multipleTable"
        :data="cart"
        style="width: 100%"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange">
      >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="productName"
          label="菜品Id"
          width="120">
        <template slot-scope="scope">{{ scope.row.productId }}</template>
      </el-table-column>
      <el-table-column
          prop="productName"
          label="菜品名"
          width="120">
        <template slot-scope="scope">{{ scope.row.productName }}</template>
      </el-table-column>
      <el-table-column
          prop="productPrice"
          label="菜品价格"
          width="120">
        <template slot-scope="scope">{{ scope.row.productPrice }}</template>
      </el-table-column>
      <el-table-column
          prop="quantity"
          label="菜品数量"
          show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.quantity }}</template>

      </el-table-column>
      <el-table-column
          prop="remark"
          label="用户偏好"
          show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.remark }}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">修改
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="修改菜品信息" :visible.sync="dialogUpdateFormVisible" width="500px">
      <el-form ref="form" :model="updateCartForm" label-width="80px" size="mini" :rules="rules">
        <el-form-item label="数量" prop="productType">
          <el-input-number v-model="updateCartForm.quantity" min="0" max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="偏好" prop="productName">
          <el-input v-model="updateCartForm.remark"></el-input>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="onUpdateFormSubmit">提交</el-button>
          <el-button @click="onUpdateFormCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <span>总价： {{ totalPrice }} 元       </span>
    <el-button type="primary" @click="submitOrder">提交订单</el-button>


  </div>
</template>

<script>
import {delCartProduct, getCartList, getCartPrice, submitOrder, updateCartProduct} from "@/API/UserAPI";
import message from "@/utils/message";
import {deleteProduct, getProduct} from "@/API/ProductAPI";
import Message from "@/utils/message";

export default {
  data() {
    return {
      dialogUpdateFormVisible: false,
      cart: [],
      getCartRetData: [],
      totalPrice: 0,
      orderId: "",
      updateCartForm: {
        productId: '',
        quantity: 0,
        remark: "",
      },
      rules: {
        quantity: [
          {required: true, message: '请输入数量!', trigger: 'blur'}
        ],
      }
    };
  },
  async mounted() {
    await this.getCartlist();
    await this.calculateTotalPrice();

  },
  methods: {
    async getCartlist() {
      const result = await getCartList();
      if (result.code === 1) {
        // 获取 data 中的值
        const dataValues = result.data;
        let i = 0;
        for (const key in dataValues) {
          if (Object.hasOwnProperty.call(dataValues, key)) {
            // 在这里你可以对每个值进行操作
            const thisProductResult = await getProduct(key)
            const thisProduct = thisProductResult.data;

            const cartData = {
              productId: thisProduct.productId,
              productName: thisProduct.productName,
              productPrice: thisProduct.productPrice,
              quantity: dataValues[key].quantity,
              remark: dataValues[key].remark ? dataValues[key].remark : "无",
            }
            this.$set(this.cart, i, cartData);
            i++;
          }
        }
        message.success(this, "获取购物车成功.");
      }
    },
    async submitOrder() {
      const result = await submitOrder();
      if(result.code === 1){
        console.log(result.data);
        await this.$router.push({
          name: "Payment",
          params: {
            orderId: result.data,
          },
        });
      }
    },
    handleEdit(index, row) {
      this.dialogUpdateFormVisible = true;
      this.updateCartForm.productId = row.productId;
      this.updateCartForm.quantity = row.quantity;
      this.updateCartForm.remark = row.remark;
    },
    handleDelete(index, row) {
      this.$confirm('此操作将从购物车中移除该菜品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 调用删除接口,重新加载
        const result = await delCartProduct(row.productId);
        if (result.code === 1) {
          await this.getCartlist();
          await this.calculateTotalPrice();
          message.success(this, "删除成功.");
        } else {
          message.error(this, result.description);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        });
      })
    },
    async onUpdateFormSubmit() {
      const result = await updateCartProduct(this.updateCartForm);
      if (result.code === 1) {
        message.success(this, "更新购物车成功!");
        await this.getCartlist();
        this.dialogUpdateFormVisible = false;
      } else {
        message.error(this, result.description);
      }
      await this.calculateTotalPrice();
    },
    onUpdateFormCancel() {
      this.dialogUpdateFormVisible = false;
    },

    async calculateTotalPrice() {
      const result = await getCartPrice(this.cart)
      if (result.code === 1) {
        this.totalPrice = parseFloat(result.data);
      } else {
        message.error(this,result.description);
      }

    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  }
};
</script>

<style>
.el-table {
  height: 20%;
  line-height: 20px;
}
</style>
